<?php
/**
 * Created by 1971599474@qq.com
 * User: zhixuan
 * Date: 2020/1/23
 * Time: 9:01
 */

namespace app\common\event;


use app\common\model\Brand;
use app\common\model\Goods;
use app\common\model\GoodsAttr;
use app\common\model\GoodsAttribute;
use app\common\model\Spec;
use app\common\model\SpecGoodsPrice;
use app\common\model\SpecItem;
use think\facade\Db;

class GoodsEvent
{

    public static function getGoodsIdBySpec($spec)
    {
        if (empty($spec))
            return array();

        $spec_group = explode('@', $spec);
        $where = " where 1=1 ";
        foreach ($spec_group as $k => $v) {
            $spec_group2 = explode('_', $v);
            array_shift($spec_group2);
            $like = array();
            foreach ($spec_group2 as $k2 => $v2) {
                $v2 = addslashes($v2);
                $like[] = " key2  like '%\_$v2\_%' ";
            }
            $where .= " and (" . implode('or', $like) . ") ";
        }
        $sql = "select * from (select *,concat('_',`key`,'_') as key2 from ptf_spec_goods_price as a) b  $where";
        $result = Db::query($sql);
        $arr = get_arr_column($result, 'goods_id');  // 只获取商品id 那一列
        //print_r($arr);
        return ($arr ? $arr : array_unique($arr));
    }

    /**
     * @param $attr|属性
     * @return array|mixed
     * 根据属性 查找 商品id
     * 59_直板_翻盖
     * 80_BT4.0_BT4.1
     */
    public static function getGoodsIdByAttr($attr)
    {
        if (empty($attr))
            return [];

        $attr_group = explode('@', $attr);

        $attr_id = $attr_value = [];
        foreach ($attr_group as $k => $v) {
            $attr_group2 = explode('_', $v);
            $attr_id[] = array_shift($attr_group2);
            $attr_value = array_merge($attr_value, $attr_group2);
        }

        $c = count($attr_id) - 1;
        if ($c > 0) {
            $arr = Db::name('goods_attr')
                ->where([['attr_id','in',$attr_id],['attr_value','in',$attr_value]])
                ->group('goods_id')
                ->having("count(goods_id) > $c")
                ->column("goods_id",'goods_attr_id');
        }else{
            $arr = Db::name('goods_attr')
                ->where([['attr_id','in',$attr_id],['attr_value','in',$attr_value]])
                ->column("goods_id",'goods_attr_id'); // 如果只有一个条件不再进行分组查询
        }

        return ($arr ? $arr : array_unique($arr));
    }


    public static function get_filter_spec($goods_id_arr, $filter_param, $action, $mode = 0){

        $spec_keys = SpecGoodsPrice::field("group_concat(`key` separator  '_') as `key`")->where([['goods_id','in',$goods_id_arr]])->find()->toArray();
        $spec_key = explode('_', $spec_keys['key']);
        $spec_key = array_unique($spec_key);
        $spec_key = array_filter($spec_key);
        if (empty($spec_key)) {
            if ($mode == 1) return array();
            return array('status' => 1, 'msg' => '', 'result' => array());
        }
        $spec = Spec::where(['search_index'=>1])->column('name','id');
        $spec_item = SpecItem::where([['spec_id','in',array_keys($spec)]])->column('spec_id,item','id');
        //print_r($spec_item);die();
        $old_spec = isset($filter_param['spec'])?$filter_param['spec']:'';
        $list_spec = [];
        foreach ($spec_key as $k => $v) {
            if (strpos($old_spec, $spec_item[$v]['spec_id'] . '_') === 0 || strpos($old_spec, '@' . $spec_item[$v]['spec_id'] . '_') || $spec_item[$v]['spec_id'] == '')
                continue;
            $list_spec[$spec_item[$v]['spec_id']]['spec_id'] = $spec_item[$v]['spec_id'];
            $list_spec[$spec_item[$v]['spec_id']]['name'] = $spec[$spec_item[$v]['spec_id']];
            //$list_spec[$spec_item[$v]['spec_id']]['item'][$v] = $spec_item[$v]['item'];

            // 帅选参数
            if (!empty($old_spec)) {
                $filter_param['spec'] = $old_spec . '@' . $spec_item[$v]['spec_id'] . '_' . $v;
            }else {
                $filter_param['spec'] = $spec_item[$v]['spec_id'] . '_' . $v;
                $list_spec[$spec_item[$v]['spec_id']]['item'][] = array('key' => $spec_item[$v]['spec_id'], 'val' => $v, 'item' => $spec_item[$v]['item'], 'href' => urldecode(url("index/goods/goodsList", $filter_param)));
            }
        }
        if ($mode == 1) return $list_spec;
        return array('status' => 1, 'msg' => '', 'result' => $list_spec);
    }

    public static function get_filter_attr($goods_id_arr, $filter_param, $action, $mode = 0)
    {
        $goods_id_str = implode(',', $goods_id_arr);
        $goods_id_str = $goods_id_str ? $goods_id_str : '0';

        $goods_attr = GoodsAttr::where([['goods_id','in',$goods_id_str],['attr_value','<>','']])->select()->toArray();
        // $goods_attr = M('goods_attr')->where("attr_value != ''")->select();
        $goods_attribute = GoodsAttribute::where("attr_index = 1")->column('attr_id,attr_name,attr_index','attr_id');
        //print_r($goods_attribute);
        if (empty($goods_attr)) {
            if ($mode == 1) return [];
            return array('status' => 1, 'msg' => '', 'result' =>[]);
        }
        $list_attr = $attr_value_arr = [];
        $old_attr = isset($filter_param['attr'])?$filter_param['attr']:'';

        foreach ($goods_attr as $k => $v) {
            // 存在的筛选不再显示
            if (strpos($old_attr, $v['attr_id'] . '_') === 0 || strpos($old_attr, '@' . $v['attr_id'] . '_'))
                continue;
            if ($goods_attribute[$v['attr_id']]['attr_index'] == 0)
                continue;
            $v['attr_value'] = trim($v['attr_value']);
            // 如果同一个属性id 的属性值存储过了 就不再存贮
            if (in_array($v['attr_id'] . '_' . $v['attr_value'], @(array)$attr_value_arr[$v['attr_id']]))
                continue;
            $attr_value_arr[$v['attr_id']][] = $v['attr_id'] . '_' . $v['attr_value'];

            $list_attr[$v['attr_id']]['attr_id'] = $v['attr_id'];
            $list_attr[$v['attr_id']]['attr_name'] = $goods_attribute[$v['attr_id']]['attr_name'];

            // 筛选参数
            if (!empty($old_attr))
                $filter_param['attr'] = urlencode($old_attr . '@' . $v['attr_id'] . '_' . $v['attr_value']);
            else
                $filter_param['attr'] = urlencode($v['attr_id'] . '_' . $v['attr_value']);

            $list_attr[$v['attr_id']]['attr_value'][] = array('key' => $v['attr_id'], 'val' => $v['attr_value'], 'attr_value' => $v['attr_value'], 'href' => urldecode(url("index/goods/$action", $filter_param)));
            //unset($filter_param['attr_id_'.$v['attr_id']]);
        }
        if ($mode == 1) return $list_attr;
        return array('status' => 1, 'msg' => '', 'result' => $list_attr);
    }

    /**
     * @param  $brand_id|帅选品牌id
     * @param  $price|帅选价格
     * @return array|mixed
     */
    public static function getGoodsIdByBrandPrice($brand_id, $price)
    {
        if (empty($brand_id) && empty($price))
            return array();
        $brand_select_goods=$price_select_goods=array();
        if ($brand_id) // 品牌查询
        {
            $brand_id_arr = explode('_', $brand_id);

            $brand_select_goods = Goods::whereIn('brand_id',$brand_id_arr,'or')->column('goods_id', 'goods_id');
        }
        if ($price)// 价格查询
        {
            $price = explode('-', $price);
            $price[0] = intval($price[0]);
            $price[1] = intval($price[1]);
            $price_where=" shop_price >= $price[0] and shop_price <= $price[1] ";
            $price_select_goods = Goods::where($price_where)->column('goods_id', 'goods_id');
        }
        if($brand_select_goods && $price_select_goods)
            $arr = array_intersect($brand_select_goods,$price_select_goods);
        else
            $arr = array_merge($brand_select_goods,$price_select_goods);
        return $arr ? $arr : array();
    }


    /**
     * 筛选的价格区间
     * @param $goods_id_arr|帅选的分类id
     * @param $filter_param
     * @param $action
     * @param int $c 分几段 默认分5 段
     * @return array
     */
    public static function get_filter_price($goods_id_arr, $filter_param, $action, $c = 5)
    {

        if (!empty($filter_param['price']))
            return [];

        $goods_id_str = implode(',', $goods_id_arr);
        $goods_id_str = $goods_id_str ? $goods_id_str : '0';
        $priceList = Goods::where("goods_id", "in", $goods_id_str)->column('shop_price','goods_id');  //where("goods_id in($goods_id_str)")->select();

        if(empty($priceList)){
            return [];
        }
        rsort($priceList);
        $max_price = (int)$priceList[0];

        $psize = ceil($max_price / $c); // 每一段累积的价钱
        $parr = array();
        for ($i = 0; $i < $c; $i++) {
            $start = $i * $psize;
            $end = $start + $psize;

            // 如果没有这个价格范围的商品则不列出来
            $in = false;
            foreach ($priceList as $k => $v) {
                if ($v > $start && $v < $end)
                    $in = true;
            }
            if ($in == false)
                continue;

            $filter_param['price'] = "{$start}-{$end}";
            if ($i == 0)
                $parr[] = array('value' => "{$end}元以下", 'href' => urldecode(url("index/goods/$action", $filter_param, '')));
            elseif($i == ($c-1) && ($max_price > $end))
                $parr[] = array('value' => "{$end}元以上", 'href' => urldecode(url("index/goods/$action", $filter_param, '')));
            else
                $parr[] = array('value' => "{$start}-{$end}元", 'href' => urldecode(url("index/goods/$action", $filter_param, '')));
        }
        return $parr;
    }

    /**
    * @param $goods_id_arr
    * @param $filter_param
    * @param $action
    * @return array|mixed 这里状态一般都为1 result 不是返回数据 就是空
    * 获取 商品列表页帅选品牌
    */
    public static function get_filter_brand($goods_id_arr, $filter_param, $action)
    {
        if (!empty($filter_param['brand_id'])) {
            return array();
        }

        $map[] = ['goods_id','in', $goods_id_arr];
        $map[] = ['brand_id','>', 0];
        $brand_id_arr = Goods::where($map)->column('brand_id','goods_id');

        $list_brand = Brand::where('id','in',$brand_id_arr)->limit('30')->select()->toArray();
        foreach ($list_brand as $k => $v) {
            // 帅选参数
            $filter_param['brand_id'] = $v['id'];
            $list_brand[$k]['href'] = urldecode(url("index/goods/$action", $filter_param, ''));
        }

        return $list_brand;
    }

    /**
     * 筛选条件菜单
     * @param $filter_param
     * @param $action
     * @return array
     */
    public static function get_filter_menu($filter_param, $action)
    {
        $menu_list = array();
        // 品牌
        if (!empty($filter_param['brand_id'])) {
            $brand_list = Brand::column('name','id');
            $brand_id = explode('_', $filter_param['brand_id']);
            $brand['text'] = "品牌:";
            foreach ($brand_id as $k => $v) {
                $brand['text'] .= $brand_list[$v] . ',';
            }
            $brand['text'] = substr($brand['text'], 0, -1);
            $tmp = $filter_param;
            unset($tmp['brand_id']); // 当前的参数不再带入
            $brand['href'] = urldecode(url("index/goods/$action", $tmp, ''));
            $menu_list[] = $brand;
        }
        // 规格
        if (!empty($filter_param['spec'])) {
            $spec = Spec::column('name','id');
            $spec_item = SpecItem::column('item','id');
            $spec_group = explode('@', $filter_param['spec']);
            foreach ($spec_group as $k => $v) {
                $spec_group2 = explode('_', $v);
                $spec_menu['text'] = $spec[$spec_group2[0]] . ':';
                array_shift($spec_group2); // 弹出第一个规格名称
                foreach ($spec_group2 as $k2 => $v2) {
                    $spec_menu['text'] .= $spec_item[$v2] . ',';
                }
                $spec_menu['text'] = substr($spec_menu['text'], 0, -1);

                $tmp = $spec_group;
                $tmp2 = $filter_param;
                unset($tmp[$k]);
                $tmp2['spec'] = implode('@', $tmp); // 当前的参数不再带入
                $spec_menu['href'] = urldecode(url("index/goods/$action", $tmp2, ''));
                $menu_list[] = $spec_menu;
            }
        }
        // 属性
        if (!empty($filter_param['attr'])) {
            $goods_attribute = GoodsAttribute::column('attr_name','attr_id');
            $attr_group = explode('@', $filter_param['attr']);
            foreach ($attr_group as $k => $v) {
                $attr_group2 = explode('_', $v);
                $attr_menu['text'] = $goods_attribute[$attr_group2[0]] . ':';
                array_shift($attr_group2); // 弹出第一个规格名称
                foreach ($attr_group2 as $k2 => $v2) {
                    $attr_menu['text'] .= $v2 . ',';
                }
                $attr_menu['text'] = substr($attr_menu['text'], 0, -1);

                $tmp = $attr_group;
                $tmp2 = $filter_param;
                unset($tmp[$k]);
                $tmp2['attr'] = implode('@', $tmp); // 当前的参数不再带入
                $attr_menu['href'] = urldecode(url("index/goods/$action", $tmp2, ''));
                $menu_list[] = $attr_menu;
            }
        }
        // 价格
        if (!empty($filter_param['price'])) {
            $price_menu['text'] = "价格:" . $filter_param['price'];
            unset($filter_param['price']);
            $price_menu['href'] = urldecode(url("index/goods/$action", $filter_param, ''));
            $menu_list[] = $price_menu;
        }

        return $menu_list;
    }
}